package logic

import (
	"context"
	"crypto/md5"
	"fmt"
	"net/http"

	"zero_six/user/internal/svc"
	"zero_six/user/pb/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 格式 rpc 名称（服务的请求参数）returns(响应参数)
func (l *LoginLogic) Login(in *user.Request) (*user.Response, error) {
	// todo: add your logic here and delete this line

	fmt.Println("接收到的用户名")
	fmt.Println(in.Username)

	//userInfo, err := l.svcCtx.UserModel.FindOne(context.Background(), 1)
	userInfo, err := l.svcCtx.UserModel.FindByUsername(context.Background(), in.Username)

	if err != nil {
		fmt.Println(err)
		return &user.Response{
			Code: http.StatusCreated,
			Msg:  "userinfo not found ",
		}, nil
	}
	fmt.Println(userInfo)

	encrypt_password := fmt.Sprintf("%x", md5.Sum([]byte(in.Password)))
	fmt.Println(encrypt_password) // 加密后的密码、和数据库对比
	if userInfo.Password != encrypt_password {
		fmt.Println("密码不一致")
		return &user.Response{
			Code: http.StatusCreated,
			Msg:  "password error",
		}, nil
	}

	return &user.Response{
		Code:     http.StatusOK,
		Msg:      "login success",
		UserId:   userInfo.Id,
		Username: userInfo.Username,
	}, nil
}
